<template>
	<div class="main">
		<div class="main-header" style="display: flex;justify-content: space-between;">
			<div style="display: flex;flex:1;flex-wrap: wrap;align-items: center;">
				<el-input v-model="searchParamCp.keyword" placeholder="请输入商家名称或联系人" style="width:200px;margin-right: 10px;"></el-input>
				<el-select v-model="searchParamCp.cate_id"  placeholder="请选择分类"
					style="width: 200px;">
					<el-option v-for="(item,index) in catelist" :key="index" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
				<!-- <div style="margin: 0 0 0 20px;">派发时间：</div>
				<el-date-picker style="max-width: 300px;" clearable class="ml-10" v-model="searchParamCp.search_time"
					type="datetimerange" value-format="yyyy-MM-dd" :picker-options="pickerOptions" range-separator="至"
					start-placeholder="开始日期" end-placeholder="结束日期" align="right">
				</el-date-picker> -->
				<div style="margin-left: 10px;">
					<el-button type="primary" @click="searchinfo">搜索</el-button>
					<el-button type="primary" @click="reset">重置</el-button>
				</div>
			</div>
			<div style="display: flex;">
				<div class="main-header" v-if="buttons.length">
					<elUploadFile style="margin-right: 10px;"  :title="'导入'" :auto-upload="false" :upload-clear="true"
						:show-file-list="false" @change="upload" :limit="1" :multiple="false" accept=".xls,.xlsx" class="ml-10">
						<el-button type="primary">导入</el-button>
					</elUploadFile>
				    <el-button v-for="(item, index) in buttons" :key="index" :type="item.path | formatType" :icon="item.icon"
				        :disabled="item.path | formatDisabled(selection)" @click="tapButton(item)">{{ item.title }}</el-button>
				</div>
			<!-- 	<el-button v-if="$auth('add')" type="primary" @click="addStore">添加</el-button>
				<el-button v-if="$auth('delete')" type="danger" @click="selectdel"
					:disabled="!selection.length">批量删除</el-button> -->
			</div>
		</div>
		<el-table ref="table" class="main-table" header-align="center" border :data="list"
			@selection-change="onSelectionChange" height="100%" row-key="id" header-cell-class-name="main-table-header"
			@row-click="onRowClick">
			<el-table-column type="selection" :reserve-selection="true"  width="50"> </el-table-column>
			<el-table-column label="商家logo" prop="merch_picarr" width="110">
				<template slot-scope="{row}">
					<el-image :src="row.merch_picarr.split(',')[0]" style="width: 80px;height: 80px;" />
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip label="商家名称" prop="merch_name" width="160"></el-table-column>
			<el-table-column show-overflow-tooltip label="会员号" prop="member_no" width="160"></el-table-column>
			<el-table-column show-overflow-tooltip label="联系人" prop="merch_link_man" width="160"></el-table-column>
			<el-table-column show-overflow-tooltip label="联系电话" prop="mobile" width="160" ></el-table-column>
			<el-table-column show-overflow-tooltip label="商家编号" prop="channel_merchant_no" width="160" ></el-table-column>
			<el-table-column show-overflow-tooltip label="终端号" prop="channel_terminal_no"  width="160"></el-table-column>
			<el-table-column label="商家码" prop="merch_code" width="110">
				<template slot-scope="{row}">
					<el-image :src="'https://zdcloud.zxkjnc.com'+row.merch_code" style="width: 80px;height: 80px;" :preview-src-list="['https://zdcloud.zxkjnc.com'+row.merch_code]" />
				</template>
			</el-table-column>
			<!-- <el-table-column show-overflow-tooltip label="地址" prop="address"></el-table-column> -->
			<el-table-column show-overflow-tooltip label="商户登录账号"  width="160">
				<template slot-scope="{row}">
					<div class="line-one">
						<p>{{ row.username }}</p>
						<!-- <p>{{ row.house_num }}</p> -->
					</div>
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip label="营业时间" prop="cadre_mobile" width="160">
				<template slot-scope="{row}">
					{{ row.opening_time }}
				</template>
			</el-table-column>
			<!-- is_split 0否 1是 -->
			<el-table-column show-overflow-tooltip label="分账账户" prop="cadre_mobile" width="120">
				<template slot-scope="{row}">
					<el-tag v-if="row.is_split==1">是</el-tag>
					<el-tag v-if="row.is_split==0">否</el-tag>
				</template>
			</el-table-column>
			<!-- 进件状态 0创建 1审核中 2进件中 3有效 4驳回 -->
			<el-table-column show-overflow-tooltip label="进件状态" prop="lkl_merch_status" width="120px">
				<template slot-scope="{row}">
					<el-tag v-if="row.lkl_merch_status==1">审核中</el-tag>
					<el-tag v-if="row.lkl_merch_status==0">创建</el-tag>
					<el-tag v-if="row.lkl_merch_status==2">进件中</el-tag>
					<el-tag v-if="row.lkl_merch_status==3">有效</el-tag>
					<el-tag v-if="row.lkl_merch_status==4">驳回</el-tag>
					<div v-if="row.lkl_merch_status==4">{{row.lkl_err_msg}}</div>
				</template>
			</el-table-column>
			<!-- open_part  1普通会员 2收单商户 -->
			<el-table-column show-overflow-tooltip label="开通角色" prop="open_part" width="130">
				<template slot-scope="{row}">
					<el-tag v-if="row.open_part==1" type="success">普通会员</el-tag>
					<el-tag v-if="row.open_part==2" type="danger">收单商户</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="创建时间" prop="createtime" width="150">
													<template slot-scope="{row}">
														{{ row.createtime | formatDate }}
													</template>
												</el-table-column>
			<el-table-column label="操作" width="230px" align="center" fixed="right">
				<template slot-scope="{row}">
					<el-button type="success" size="mini" @click.stop="becoed(row)">生成商家码</el-button>
					<el-button type="warning" size="mini" @click.stop="edit(row)">编辑</el-button>
					<el-button type="danger" size="mini" :disabled="row.is_split==1" @click.stop="setpassword(row)">设置分账账户</el-button>
					
					<el-button type="primary" size="mini" style="margin-top: 10px;" :disabled="row.lkl_merch_status==3" @click.stop="drup(row)">去进件</el-button>
					<el-button type="danger" size="mini"  style="margin-top: 10px;"  @click.stop="newlink(row)" >重置进件链接</el-button>
					<el-button type="info" size="mini"  style="margin-top: 10px;"  @click.stop="setdiscount(row)" >设置折扣</el-button>
					<!--  -->
				</template>
			</el-table-column>
		</el-table>
		<el-pagination class="main-pagination" :current-page.sync="searchParam.page" :page-size="searchParam.limit"
			:total="searchParam.total" @current-change="onCurrentChange"
			layout="total,jumper,prev,pager,next"></el-pagination>

		<!-- 添加/编辑弹窗 -->
		<addEdit  ref="addEditDialog" :floorlist="floorlist" :editInfo.sync="editInfo" :title="title" @confirm="getList"></addEdit>
		<discount ref="discountDialog" :floorlist="floorlist" :id="fromid" :editInfo.sync="editInfo" :title="title" @confirm="getList"></discount>
	</div>
</template>
<script>
import { get, post ,del,imghttp} from '@/assets/js/http'
import addEdit from './components/addEdit.vue'
import discount from './components/discount.vue'
import elUploadFile from '@/components/el-upload-file.vue';
export default {
	components: { addEdit ,elUploadFile,discount},
	props:{
		astatus:{
			type:String,
			defaulit:''
		}
	},
	data() {
		return {
			list: [],
			selection: [],
			floorlist:[],//楼层列表
			editInfo:null,
			title:'',//弹窗标题
			searchParam: {
				page: 1,
				limit: 20,
				total: 0,
				cadre_id: '',
				search_time: [],
				status: this.astatus||'',
				cate_id: '',
				keyword: '',
			},
			searchParamCp: {
			},
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			},
			catelist:[],
			fromid:'',
		}
	},
	created() {
		this.getList()
		this.getfloor()
		this.getGoodsTypeData()
	},
	computed: {
	    buttons() {
	        return this.$store.state.buttons;
	    }
	},
	methods: {
		async getList() {
			this.$loading()
			await get({
				url: '/admin/store.merchant/index',
				params: {
					...this.searchParam,
					...{
						search_time: this.searchParam.search_time.length ? this.searchParam.search_time.join(' - ') : ''
					}
				}
			}).then(res => {
				this.list = res.list
				this.searchParam.total = res.total
				this.$loading().close()
			})
		},
		async getGoodsTypeData() {
		    const data = await get({
		        url: "/admin/store.MerchantCate/index",
		        loading: true,
		        params: {
		            page: 1,
		            limit: 9999
		        }
		    });
		    data.list.forEach((item) => {
		        let findParent = data.list.find(i => i.id == item.parent_id)
		        if (findParent) {
		            findParent.children = [...(findParent.children || []), item]
		        }
		    })
		    data.list = data.list.filter(item => item.parent_id == 0)
		    this.$nextTick(() => {
		        this.catelist = data.list;
		        // this.total = data.total;
		    })
		},
		edit(row){//cate_id
			this.title = '修改商家'
			
			this.editInfo = row
			this.editInfo.location = { lat:this.editInfo.latitude,lng:this.editInfo.longitude}
			if(row.tags){
				this.editInfo.tags = row.tags.split(',')
				this.editInfo.tags = this.editInfo.tags.join(' ')
			}
			console.log(row,'row')
			this.$refs.addEditDialog.open()
		},
		addStore(){
			this.title = '添加商家'
			this.editInfo = null
			this.$refs.addEditDialog.open()
		},
		//设置折扣
		setdiscount(row){
			this.fromid = row.id
			this.title = '设置折扣'
			this.editInfo = null
			this.$refs.discountDialog.open()
		},
		reset() {
			this.searchParamCp = this.$options.data().searchParam
			this.searchParam = this.$options.data().searchParam
			this.getList()
		},
		searchinfo() {
			this.searchParam.page = 1
			this.searchParam = { ...this.searchParam, ...this.searchParamCp }
			this.getList()
		},
		onCurrentChange() {
			this.getList()
		},
		onRowClick(row) {
			this.$refs.table.toggleRowSelection(row);
		},
		onSelectionChange(selection) {
			this.selection = selection;
			console.log(selection,this.selection)
			this.$emit('handleselect',this.selection)
		},
		setpassword(row){
			this.$confirm('是否把该账户设为分账账户?', '提示', {
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning'
				}).then(() => {
					post({
						url:'/admin/store.merchant/setSplit',
						data:{
							id:row.id,
						},
						successTip: true,
					}).then(res=>{
						this.getList()
					})
				}).catch(action => {
					if(action === 'cancel'){
						this.$message({
							type: 'info',
							message: '已取消'
						}); 
					}
					else{
						
					}
				        
				});
		},
		selectdel() {
			this.$confirm(
				`此操作将永久删除该${this.selection.length}个商家, 是否继续?`,
				"提示",
				{
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}
			)
				.then(async () => {
					let query = "?";
					for (let i = 0; i < this.selection.length; i++) {
						const item = this.selection[i];
						if (i > 0) {
							query += "&ids[]=" + item.id;
						} else {
							query += "ids[]=" + item.id;
						}
					}
					await del({
						url: "/admin/store.merchant/del" + query,
						successTip: true,
						loading: true
					});
					this.getList()
				})
				.catch(() => {
					this.$refs.table.clearSelection();
				});
		},
		getfloor(){
			post({
				url:'/api/Wechat/buildFloor'
			}).then(res=>{
				this.floorlist = res
			})
		},
		//去进帐
		drup(row){
			this.$confirm('请在2小时内完成进件资料填写，逾期链接作废?', '提示', {
				confirmButtonText: '去进帐',
				cancelButtonText: '取消',
				type: 'warning'
				}).then(() => {
					window.open(row.lkl_open_url)
				}).catch(action => {
					if(action === 'cancel'){
						this.$message({
							type: 'info',
							message: '已取消'
						}); 
					}
					else{
						
					}
				        
				});
		},
		//充值进件链接
		newlink(row){
			get({
				url:'/admin/store.merchant/getNewLklMemberOpenUrl',
				params:{
					id:row.id
				},
				successTip: true,
			}).then(res=>{
				this.getList()
			})
		},
		//导入
		async upload({ raw }) {
			console.log(raw, 'raw')//info
			this.$loading({
				text: '导入中 请等待...'
			})
			await imghttp({
				url: '/admin/store.merchant/import',
				data: {
					file: raw
				},
				successTip: true
			})
			this.getList()
			this.$loading().close()
		},
		tapButton(item) {
		    if (item.path === "add") {
		        this.addStore();
		    } else if (item.path === "edit") {
		        this.onEdit();
		    } else if (item.path === "delete") {
		        this.selectdel();
		    }
		},
		//生成商家码
		becoed(row){
			get({
				url:'/admin/store.merchant/createMerchCode',
				params:{
					id:row.id,
				},
				successTip: true
			}).then(res=>{
				this.getList()
			})
		}
	}
}
</script>

<style >
.el-date-editor .el-range-separator {
	padding: 0;
}
</style>